# -*-enconding:utf-8 -*-
import os
import cv2
from sklearn import preprocessing
from sklearn import decomposition
import numpy as npy
import time
import shutil

def get_face_by_camera(name):
    face = cv2.CascadeClassifier("./haarcascade_frontalface_alt.xml")
    path = f"./faces/train/{name}/"
    n = 300
    cap = cv2.VideoCapture(0)
    nCount = 0
    while True:
        ret, img =  cap.read()
        img = cv2.resize(img, None, fx = 1, fy = 1)
        img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        face_area =  face.detectMultiScale(img, 1.5, 5)
        for (x, y, w, h) in face_area:
            cv2.imwrite(path + str(nCount) + ".jpg", img_gray)
            nCount += 1
            print("Get Pics Count: " + str(nCount))
        if (nCount > n):
            break
        cv2.imshow("My Capture", img)
        time.sleep(0.2)
        key = cv2.waitKey(1)
        if (key == ord("q")):
            break


def face_pics_collection():
    face_dataset_path = os.path.join('.', 'face_dataset', 'train')
    print("欢迎使用人脸图片采集系统")
    face_load_path = input("请输入需要加载的图片路径（路径内可以包含多个人脸图片文件夹，使用摄像头获取请直接按回车）: \n")
    if 0 != len(face_load_path):
        if os.path.exists(face_load_path):
            face_docs = [doc for doc in os.listdir(face_load_path) if os.path.isdir(os.path.join(face_load_path, doc))]
            for doc in face_docs:
                shutil.copytree(os.path.join(face_load_path, doc), os.path.join(face_dataset_path, doc))
        else:
            print("路径不存在")
        return 0

    while True:
        face_name = input("请输入您的姓名: \n")
        if 0 != len(face_name):
            print("Hello, ", face_name)
            get_face_by_camera(face_name)
            break

    # while True:
    #     key = input("准备好摄像头以后，请按回车继续\n")
    #     # if 0 != len(key):
    #     if 13 == ord(key):
    #         break
    print("face_pics_collection done")

if __name__ == '__main__':
    face_pics_collection()

